const { app, ipcMain, dialog } = require('electron')
const { taskConfig } = require('./task')
const { BASE_APP_URL, store, FONTS_PATH, APP_DATA_DIR_NAME } = require('./helper')
const { address } = require('./utils')
const fs = require('fs')
const path = require('path')
const initIPC = () => {

    // 获取应用信息
    ipcMain.handle("api:getInfo", (event, arg) => {
        return {
            version: app.getVersion(),
            webHttp: BASE_APP_URL,
            deviceId: address.machineId,
            printing: taskConfig.printing,
            appDataDirName: APP_DATA_DIR_NAME,
        }
    });
    // 创建打印窗口
    ipcMain.on('createPrintWindow', (event, arg) => {
        global.PRINT_WINDOW = createPrintWindow();
        event.sender.send("createPrintWindow", arg);
    });

    // 获取打印机列表
    ipcMain.handle("api:getPrinters", async (event, arg) => {
        const list = await global.PRINT_WINDOW.webContents.getPrintersAsync();
        return list;
    });

    // 获取本地字体列表
    ipcMain.handle("api:getLocalFonts", async (event, arg) => {

        // 获取指定目录下的字体列表
        const fontPath = path.join(FONTS_PATH)
        // 读取指定目录下的文件
        const list = fs.readdirSync(fontPath)
        // 返回字体列表 [{name:""}]
        return list.map(item => ({ name: item }))
    });

    // 监听渲染进程请求选择目录
    ipcMain.handle('api:selectDirectory', async (event, arg) => {
        const result = await dialog.showOpenDialog(Object.assign({
            title: '选择目录',
            defaultPath: arg.defaultPath || undefined, // 若有记录则使用
            properties: ['openDirectory']
        }, arg));
        if (!result.canceled && result.filePaths.length > 0) {
            return result.filePaths[0]; // 保存为下次默认目录
        }
        return null;
    });

    //重启
    ipcMain.handle('api:restart', async (event, arg) => {
        app.relaunch()
        app.exit(0)
    })


    // tts 语音服务
    ipcMain.on('tts:render:speak', (event, arg) => {
        // console.log("mainWindow", global.MAIN_WINDOW);
        // console.log("tts:render:speak", arg);
        global.MAIN_WINDOW.webContents.send('tts:render:speak', arg);
    });


    // 添加同步获取数据的IPC处理程序
    ipcMain.on('electronStore:getSync', (event, key) => {
        event.returnValue = store.get(key);
    })

    // 添加同步设置数据的IPC处理程序
    ipcMain.on('electronStore:setSync', (event, key, value) => {
        event.returnValue = store.set(key, value);
    })

    // 添加同步删除数据的IPC处理程序
    ipcMain.on('electronStore:deleteSync', (event, key) => {
        if (store.get(key)) {
            event.returnValue = store.delete(key);
        } else {
            event.returnValue = null;
        }
    })


}

module.exports = {
    initIPC
}
